﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Xml;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        /// <summary>
        /// 新建文档。
        /// </summary>
        /// <param name="window">主窗口，传入Globals.MainWindow即可。</param>
        /// <param name="mainTabControl">主窗口上的主文件选项卡。</param>
        /// <param name="templateFilePath">此参数不为null时，会根据指定的模板创建文档。</param>
        public static void NewDocument(MainWindow window,
            TabControl mainTabControl, string templateFilePath = null)
        {
            //先看看有没有打开同名文件，如果有，Globals.newDocumentsCount+1,再试.
            List<string> fileNames = new List<string>();
            foreach (TabItem ti in mainTabControl.Items)
            {
                Editor e = ti as Editor;

                if (e != null)
                {
                    fileNames.Add(e.FileNameHeader.Text);
                }
            }

            string newFileDefName = "新文档 "
                + (++Globals.newDocumentsCount).ToString() + ".lpdoc";

            while (fileNames.Contains(newFileDefName))
            {
                Globals.newDocumentsCount++;
                newFileDefName = "新文档 "
                + (Globals.newDocumentsCount).ToString() + ".lpdoc";
            }

            Editor editor;

            if (templateFilePath == null)
            {
                editor = new Editor(window);
            }
            else
            {
                XmlDocument templateXmlDoc = new XmlDocument();

                //读出模板的文本。
                try
                {
                    LoadTemplateXmlDoc(templateXmlDoc, templateFilePath);
                }
                catch (Exception ex)
                {
                    Dialogs.LunarMsgBox.MsgBoxShow(
                        Globals.appName,
                        "未能顺利读取模板内容，模板文件可能已损坏。",
                        "异常信息如下：\r\n" + ex.Message,
                        ex.StackTrace, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                editor = new Editor(window, templateXmlDoc);

                LoadDocumentAttributes(editor);
            }

            mainTabControl.Items.Add(editor);

            editor.IsModified = false;
            editor.FileNameHeader.Text = newFileDefName;

            mainTabControl.SelectedIndex = mainTabControl.Items.IndexOf(editor);
            Globals.selectedEditor = editor;
            //editor.BaseScrolledViewer.Focus();

            if (window.scvOfExLayersTree.Visibility != Visibility.Visible)
            {
                window.EnableStatusControls(Visibility.Visible);
            }

            editor.ListExpressionsTreeOnStatusBar(editor.SelectedExpression);

            Globals.RefreshToolsWhenNewOrOpenDocument(editor.ParentWindow);
            editor.Focus();
            editor.IsOpened = true;//否则自动定位等功能不可用。这是防止过快操作造成的问题。
        }

        /// <summary>
        /// 从磁盘上读取模板文档的内容。模板文档实际上是导出的png格式的图片，在末尾附加了文档的xml文本。
        /// </summary>
        /// <param name="templateXmlDoc">如果传入null，会自动创建一个新实例。</param>
        /// <param name="templateFilePath">全路径。</param>
        private static void LoadTemplateXmlDoc(XmlDocument templateXmlDoc, string templateFilePath)
        {
            XmlReader reader = null;

            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ConformanceLevel = ConformanceLevel.Document;
                settings.IgnoreWhitespace = true;
                settings.IgnoreComments = true;
                reader = XmlReader.Create(/*"file:///" +加这个会出错！！*/ templateFilePath, settings);

                if (templateXmlDoc == null) { templateXmlDoc = new XmlDocument(); }

                templateXmlDoc.RemoveAll();

                //重复。 XmlReader.Create()方法会抛出此异常。
                //if (File.Exists(templateFilePath) == false)
                //{
                //    throw new Exception("指定的模板文件<" + templateFilePath + ">不存在！");
                //}

                if (templateFilePath.EndsWith(".lptemp"))
                {
                    bool start = false;
                    StringBuilder sb = new StringBuilder();
                    using (StreamReader sr = File.OpenText(templateFilePath))
                    {
                        string s = "";
                        while ((s = sr.ReadLine()) != null)
                        {
                            if (start == false)
                            {
                                if (s.EndsWith("<?Lunar Presentation?>"))
                                {
                                    start = true;
                                }

                                continue;
                            }

                            sb.Append(s);
                        }

                        if (sb.Length <= 0)
                        {
                            throw new Exception("这个文件可能不是由本程序生成的模板文件或已损坏！无法从中获取文档内容。");
                        }

                        templateXmlDoc.LoadXml(sb.ToString());
                    }
                }
                else
                {
                    throw new Exception("模板文档后缀名不为：.lptemp。");
                }
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }
    }
}
